//这是项目入口文件

// 注意 在 webpack 中导入的vue，功能不全，只提供了 runtime-only 的方式
import Vue from 'vue'
// 导入app组件
import app from './app.vue'
// 导入vue-router包
import VueRouter from 'vue-router'
// 导入router.js
import router from './router.js'

// 导入axios
import axios from './api/axios.js'

// 对http请求所带的数据进行解析
import querystring from 'querystring'

// 导入vuex
import Vuex from 'vuex'
// 注册vuex
Vue.use(Vuex)
var car = JSON.parse(localStorage.getItem('car') || '[]')   // 获取本地存储的购物车信息
var token = localStorage.getItem('token') || ''   // 获取token信息
var uid = localStorage.getItem('uid') || ''   // 获取用户标识
var store = new Vuex.Store( {
  state: {
    carInfo: car,  // 购物车商品数据
    status: '',   // 登录状态
    token: token, 
    uid: uid  // 用户id
  },
  mutations: {
    auth_request(state) {
      state.status = 'loading'
    },
    auth_success(state, users) {
      state.status = 'success'
      state.token = users.token
      state.uid = users.uid
    },
    auth_error(state, error) {
      state.status = error
    },
    auth_logout(state) {
      state.status = ''
      state.token = ''
      state.uid = ''
    },
    // 加入购物车
    addCarInfo(state, goodsInfo) {
      let flag = false  // 默认商品不存在
      state.carInfo.some(item => {
        if(item.id == goodsInfo.id){
          item.num += parseInt(goodsInfo.num)
          flag = true
          return true
        }
      })
      if(!flag) {
        state.carInfo.push(goodsInfo)
      }
      localStorage.setItem('car',JSON.stringify(state.carInfo)) // 本地存储购物车信息
    },
    // 删除购物车
    deleteCarInfo(state, goodsId) {
      state.carInfo.forEach((item, i) => {
        if(item.id == goodsId) {
          state.carInfo.splice(i,1)
        }
      })
      localStorage.setItem('car',JSON.stringify(state.carInfo))
    },
    // 选中或不选商品
    selectCarInfo(state, goodsId) {
      state.carInfo.forEach( item => {
        if(item.id == goodsId) {
          item.select = !item.select
        }
      })
      localStorage.setItem('car',JSON.stringify(state.carInfo))
    },
    // 全选或全不选
    selectAll(state) {
      let result = state.carInfo.every( item => item.select)
      if(result) {
        state.carInfo.forEach(item => {
          item.select = false
        })
      }else{
        state.carInfo.forEach(item => {
          item.select = true
        })
      }
      localStorage.setItem('car',JSON.stringify(state.carInfo))
    },
    // 修改商品数量
    amendShopNum(state, goods) {
      state.carInfo.forEach( item => {
        if(item.id == goods.id) {
          item.num = goods.num
        }
      })
      localStorage.setItem('car',JSON.stringify(state.carInfo))
    }
  },
  actions: {
    login({commit}, user) {
      return new Promise( (resolve, reject ) => {
        commit('auth_request')
        axios.post('user/m/login', querystring.stringify(user)).then( (res) => {
          console.log(res)
          if(res.data.code === 0) {
            localStorage.setItem('token', res.data.data.token)
            localStorage.setItem('uid', res.data.data.uid)
            commit('auth_success', {token: res.data.data.token, uid: res.data.data.uid })
          }else {
            commit('auth_error',res.data.msg)
            localStorage.removeItem('token')
          }
        })
        .catch( err => {
          commit('auth_error', err)
          localStorage.removeItem('token')
        })
      })
    },
    logOut({ commit, state }) {
      return new Promise( (resolve, reject ) => {
        commit('auth_request')
        axios.get('user/loginout').then( (res) => {
          if(res.data.code === 0) {
            commit('auth_logout')
            localStorage.removeItem('token')
            localStorage.removeItem('uid')
          }
        })
        .catch( err => {
          reject(err)
        })
      })
    }
  },
  getters: {
    // 判断是否登录
    isLogin: state => !!state.token,  //token存在并且不为空，则为true
    // 获取所有商品数量
    allNum: state => {
      let totleNum = 0  // 默认为0
      state.carInfo.forEach( item => {
        totleNum += parseInt(item.num)
      })
      return totleNum
    },
    // 是否全选
    allSelect: state => {
      return state.carInfo.every( item => (item.select))
    },
    // 获取所有商品价格
    totlePrice: state => {
      let m = 0
      state.carInfo.forEach(item => {
        if(item.select) {
          m += parseInt(item.price*item.num)
        }
      })
      return m
    }
  }
})

// 全局注册axios
Vue.prototype.$http = axios

// 按需导入mint-ui组件
// import { Header, Swipe, SwipeItem, Toast, Button, Lazyload } from 'mint-ui'
// 注册需要的组件
// Vue.component(Header.name, Header)
// Vue.component(Swipe.name, Swipe)
// Vue.component(SwipeItem.name, SwipeItem)
// Vue.component(Button.name, Button);
// Vue.use(Lazyload);

//全局导入mint-ui组件
import MinUi from 'mint-ui'
Vue.use(MinUi);

// 导入mui样式
import './lib/mui/css/mui.min.css'
import './lib/mui/css/icons-extra.css'

//导入图片浏览插件
import VuePreview from 'vue-preview'
Vue.use(VuePreview)

//注册路由
Vue.use(VueRouter)

// 定义全局过滤器
// 导入格式化时间插件
import momemt from "moment"
// 定义时间过滤器
Vue.filter('dateFormat', function( dataStr, pattern = "YYYY-MM-DD HH:mm:ss" ) {
  return momemt(dataStr).format(pattern)
})


var vm = new Vue({
  el: "#app",
  router,
  store,
  render: c => c(app)
})
